"""
拿到salary_Data2.csv 构建线性模型
1. 数据准备（读取数据）
2. 整理输入集，输出集
3. 构建模型
4. 训练模型
5. 测试模型
6. 模型可视化
"""
import pandas as pd
import matplotlib.pyplot as plt
import sklearn.linear_model as lm
import sklearn.metrics as sm # 评估模块
import numpy as np

# 1. 数据准备（读取数据）
data = pd.read_csv('Salary_Data2.csv')
# print(data)
# 绘制散点图
# plt.scatter(data['YearsExperience'],data['Salary'])
# plt.show()

# 2. 整理输入集，输出集
train_x = data.iloc[:,:-1]
train_y = data.iloc[:,-1]

# 3. 构建线性模型
model = lm.LinearRegression()
# 4. 训练模型
model.fit(train_x,train_y)
# 5. 测试模型
pred_train_y = model.predict(train_x)

# 创建岭回归模型
model_ridge = lm.Ridge(alpha=100)
model_ridge.fit(train_x,train_y)
pred_train_y_ridge = model_ridge.predict(train_x)

# 6. 模型可视化
plt.plot(train_x,pred_train_y,c='orangered')
plt.plot(train_x,pred_train_y_ridge,c='purple')
plt.scatter(train_x,train_y,c='dodgerblue',s=50)
# plt.show()

# 调整岭回归模型参数
test_x = train_x.iloc[:30:4]
test_y = train_y[:30:4]
pred_test_y = model_ridge.predict(test_x)
# print(sm.r2_score(test_y,pred_test_y))

params = np.arange(50,150,10)
# 拿到每一个参数，去构建模型，评估r2得分
scores = []
for param in params:
    model_ridge = lm.Ridge(alpha=param)
    model_ridge.fit(train_x,train_y)
    pred_test_y = model_ridge.predict(test_x)
    r2 = sm.r2_score(test_y,pred_test_y)
    # print('{}:-->{}'.format(param,r2))
    scores.append(r2)

df = pd.DataFrame(scores,index=params)
print('最好的模型参数为：',df.idxmax().values)



